package DataTransfer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.swing.event.EventListenerList;

/**
 * @author alek
 *
 */
public class DefaultDataTransporter implements InterfaceDataTransporter {
	private InputStream mInStr;
	private OutputStream mOutStr;
	private DataListen inputWaiter;
	private BufferedWriter outWriter;
	
	protected EventListenerList listenerList=new EventListenerList();

	public DefaultDataTransporter()
	{

	}
	

	
	public void addInputStreamListener(InputStreamListener listener) 
	{
		listenerList.add(InputStreamListener.class, listener);
	}
	
	public void removeInputStreamListener(InputStreamListener listener) {
		listenerList.remove(InputStreamListener.class, listener);
	}
	
	public class DataListen extends Thread
	{
		private BufferedReader sin;
		InputStream instr;

		DataListen(InputStream in)
		{
			instr=in;
			sin = new BufferedReader(new InputStreamReader(instr));
		}
		
		private void fireDataAvailable(InputStreamEvent evt)
		{
			Object[] listeners = listenerList.getListenerList();
			for (int i=0; i<listeners.length; i+=2) {
	            if (listeners[i]==InputStreamListener.class) {
	                ((InputStreamListener)listeners[i+1]).dataAvailable(evt);
	            }
	        }
		}
		
		public void run()                       
		{        
			String read;
			try {
				while((read=sin.readLine())!=null)
				{
					//instr.skip(read.length());
					InputStreamEvent evt=new InputStreamEvent(this,read,instr);
					fireDataAvailable(evt);
				}
			} catch (IOException e) {
				return;
			}
        }
	}

	
	public void setInputStream(InputStream input)
	{
		mInStr=input;
		inputWaiter=new DataListen(mInStr);
		inputWaiter.start();
	}
	
	public void setOutputStream(OutputStream output)
	{
		mOutStr=output;
		outWriter = new BufferedWriter(new OutputStreamWriter(mOutStr));
	}
	
	public void close()
	{

	}

	public InputStream getInputStream() {
		return mInStr;
	}

	public OutputStream getOutputStream() {
		return mOutStr;
	}
	public BufferedWriter getWriter()
	{
		return outWriter;
	}
	
	public void send(String message) {
		try {
			outWriter.write(message+"\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void flush()
	{
		try {
			outWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
